package nacos

import (
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/model"
	"github.com/nacos-group/nacos-sdk-go/v2/util"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/pkg/errors"
	"sync"
	"yxs-mall/common/properties"
)

var (
	clientConfig  constant.ClientConfig
	serverConfigs []constant.ServerConfig

	namingClient naming_client.INamingClient

	loadOnce sync.Once
)

func initServiceDiscovery() {
	loadOnce.Do(func() {
		initClientConfig()
		initServerConfig()
		initNamingClient()
	})
}

func RegisterInstance() {
	initServiceDiscovery()
	registerInstance(properties.AppConfig.Name, properties.AppConfig.Port)
}

func initClientConfig() {
	clientConfig = constant.ClientConfig{
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "./log",
		CacheDir:            "./cache",
		LogLevel:            "debug",
	}
}

func initServerConfig() {
	config := properties.NacosConfig
	serverConfigs = []constant.ServerConfig{
		{
			IpAddr: config.DiscoveryAddrIp,
			Port:   uint64(config.DiscoveryAddrPort),
		},
	}
}

func initNamingClient() {
	// 创建服务发现客户端
	var err error
	namingClient, err = clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
}

func registerInstance(serverName string, port int64) {
	success, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{
		Ip:          util.LocalIP(),
		Port:        uint64(port),
		ServiceName: serverName,
		Weight:      10,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
		Metadata:    map[string]string{"idc": "shanghai"},
		ClusterName: "DEFAULT",       // 默认值DEFAULT
		GroupName:   "DEFAULT_GROUP", // 默认值DEFAULT_GROUP
	})
	if err != nil {
		panic(err)
	}
	if !success {
		panic(errors.New("nacos服务注册发生错误"))
	}

}

func DeregisterInstance(serverName string, port int) {
	success, err := namingClient.DeregisterInstance(vo.DeregisterInstanceParam{
		Ip:          util.LocalIP(),
		Port:        uint64(port),
		ServiceName: serverName,
		Ephemeral:   true,
		Cluster:     "DEFAULT",       // 默认值DEFAULT
		GroupName:   "DEFAULT_GROUP", // 默认值DEFAULT_GROUP
	})
	if err != nil {
		panic(err)
	}
	if !success {
		panic(errors.New("nacos服务注销发生错误"))
	}
}

func GetServerInstance(serverName string) (*model.Instance, error) {
	// SelectOneHealthyInstance将会按加权随机轮询的负载均衡策略返回一个健康的实例
	// 实例必须满足的条件：health=true,enable=true and weight>0
	instance, err := namingClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
		ServiceName: serverName,
		GroupName:   "DEFAULT_GROUP",     // 默认值DEFAULT_GROUP
		Clusters:    []string{"DEFAULT"}, // 默认值DEFAULT
	})
	if err != nil {
		return nil, err
	}
	return instance, nil
}
